package com.itheima.utils;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * []
 *用户档案号唯一id生成器
 * @author : [mhr]
 * @version : [v1.0]
 * @createTime : [2025/2/11 11:00]
 */
public class RedisWorker {


    private static JedisPool jedisPool;

    static {
        try {
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            poolConfig.setMaxTotal(200);
            poolConfig.setMaxIdle(50);
            poolConfig.setTestOnBorrow(true);
            poolConfig.setTestOnReturn(true);
            jedisPool = new JedisPool(poolConfig, "192.168.88.131", 6379, 30000, "275295", 3);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to initialize JedisPool", e);
        }
    }

    private static final long BEGIN_TIMESTAMP = 1640995200L;

    private static final long COUNT_BITS = 32;

    public static long nextId(String keyPrefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        // 2.生成序列号
        // 2.1
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long count = jedisPool.getResource().incr("incr:" + keyPrefix + ":" + date);
        // 3.拼接返回
        return timestamp << COUNT_BITS | count;
    }



}
